package com.kluniv.tank;

import java.awt.Graphics;
import java.awt.Rectangle;

public class Bullet {
	private static final int SPEED = 10;
	protected static final int WIDTH = ResourceMgr.bulletD.getWidth();
	protected static final int HEIGHT = ResourceMgr.bulletD.getHeight();

	private	Rectangle rect = new Rectangle();
	
	private int x;
	private int y;
	private Dir dir;

	private boolean living = true;
	private Group group = Group.BAD;

	private TankFrame tf = null;

	public Bullet(int x, int y, Dir dir, Group group, TankFrame tf) {
		this.x = x;
		this.y = y;
		this.dir = dir;
		this.tf = tf;
		this.group = group;
		
		rect.x = this.x;
		rect.y = this.y;
		rect.width = Bullet.WIDTH;
		rect.height = Bullet.HEIGHT;
	}

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	public void paint(Graphics g) {
		if (!living)
			tf.bullets.remove(this);

		switch (dir) {
		case LEFT:
			g.drawImage(ResourceMgr.bulletL, x, y, null);
			break;
		case UP:
			g.drawImage(ResourceMgr.bulletU, x, y, null);
			break;
		case RIGHT:
			g.drawImage(ResourceMgr.bulletR, x, y, null);
			break;
		case DOWN:
			g.drawImage(ResourceMgr.bulletD, x, y, null);
			break;
		}

		move();
	}

	private void move() {
		switch (dir) {
		case UP:
			y -= SPEED;
			break;
		case DOWN:
			y += SPEED;
			break;
		case LEFT:
			x -= SPEED;
			break;
		case RIGHT:
			x += SPEED;
			break;
		default:
			break;
		}
		
		rect.x = this.x;
		rect.y = this.y;

		if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT)
			living = false;
	}

	public void collideWith(Tank tank) {
		if (this.group == tank.getGroup())
			return;

		if (rect.intersects(tank.rect)) {
			tank.die();
			this.die();
			int ex = tank.getX() + Tank.WIDTH / 2 - Bullet.WIDTH / 2;
			int ey = tank.getY() + Tank.HEIGHT / 2 - Bullet.HEIGHT / 2;
			tf.explodes.add(new Explode(ex, ey, tf));
		}
	}

	private void die() {
		living = false;
	}
}
